package org.jpass.dc.business.project.logic;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.jpass.dc.common.bean.TreeNode;
import org.jpass.dc.common.exception.ApplicationException;

public class FileService {
	
	/**
	 * 新建文件
	 * @param parentPath
	 * @param fileName
	 * @return
	 * @throws IOException
	 * @throws SecurityException
	 */
	public boolean createFile(String parentPath, String fileName) 
			throws IOException {
		return this.createFile(parentPath + '/' + fileName);
	}
	
	public boolean createFile(String path) throws IOException {
		File file = new File(path);
        if (!file.exists()) {
        	return  file.createNewFile();
        } else {
        	throw new ApplicationException("File already is exist!");  
        }
	}
	
	/**
	 * 重命名文件
	 * @param path
	 * @param newName
	 * @return
	 */
	public boolean renameFile(String path, String newName) {
		File src = new File(path);
		if (src.exists()) {
			File dest = new File(path.substring(0, path.lastIndexOf("/")) + "/" + newName);
        	return  src.renameTo(dest);
        } else {
        	throw new ApplicationException("File is not exist!");  
        }
	}
	
	public boolean isExist(String filePath) {
		return new File(filePath).exists();
	}
	
	/**
	 * 保存文件内容
	 * @param filePath
	 * @param text
	 * @throws FileNotFoundException
	 */
	public void write(String filePath, String text) throws IOException {
		PrintWriter out = new PrintWriter(
				new File(filePath).getAbsoluteFile());
		try {
			out.print(text);
		} finally {
			if (out != null) {
				out.close();
				out = null;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
            }
		}
	}
	
	/**
	 * 读取文件的内容
	 * @param path
	 * @return
	 * @throws IOException
	 */
	public String readFile(String path) throws IOException {
		File file = new File(path);
		if (file.isFile()) {
			BufferedReader reader = null;
	        StringBuffer text = new StringBuffer();
	        try {
	            reader = new BufferedReader(new FileReader(file));
	            String tempString = null;
	            // 一次读入一行，直到读入null为文件结束
	            while ((tempString = reader.readLine()) != null) {
	                // 显示行号
	            	text.append(tempString).append("\n");
	            }
	            reader.close();
	        } finally {
	            if (reader != null) {
	                reader.close();
	                reader = null;
	            }
	        }
	        
	        return text.toString();
		}
        return null;
	}
	
	/**
	 * 创建文件夹
	 * @param path
	 * @param name
	 * @return
	 * @throws IOException
	 * @throws SecurityException
	 */
	public boolean createFolder(String parentPath, String name)
			throws IOException{
		return this.createFolder(parentPath + "/" + name);
	}
	
	public boolean createFolder(String path) {
		File dir = new File(path);  
        if (!dir.exists()) {
        	return  dir.mkdir();
        } else {
        	throw new ApplicationException("Folder already is exist!");  
        }
	}
	
	/**
	 * 根据路劲创建多级目录
	 * @param path
	 * @return
	 */
	public boolean createMultiFolder(String path) {
		File dir = new File(path);  
        if (!dir.exists()) {
        	return  dir.mkdirs();
        } else {
        	throw new ApplicationException("Folder already is exist!");  
        }
	}
	
	public void delete(String path) throws IOException {
		File f = new File(path);
		if (f.exists()) {
			if(f.isDirectory()) { // 判断文件是否存在，如果存在是不是目录
				File delFile[] = f.listFiles();
				int fileLen = delFile.length;
				if(fileLen == 0) { // 如果目录下面没有文件直接删除目录
					f.delete();
				} else {
					for (int i = 0; i < fileLen; i++) {
						if (delFile[i].isDirectory()) {
							delete(delFile[i].getAbsolutePath()); // 递归调用delete方法删除子目录
						}
						delFile[i].delete();
					}
				}
			} 
			f.delete();
		} else {
			throw new FileNotFoundException(); 
		}
	}
	
	/**
	 * 取得文件夹列表
	 * @param user
	 * @param projectName
	 * @return
	 */
	public List<TreeNode> getFolderList(String path) {
		ArrayList<TreeNode> fileList = new ArrayList<TreeNode>();
		return searchFolders(path, fileList);
	}
	
	/**
	 * 递归遍历磁盘的文件夹
	 * @param path  需要遍历文件夹的根目录
	 * @param folderList 目录列表
	 * @return
	 */
	protected List<TreeNode> searchFolders(String path, List<TreeNode> folderList) {
		File dir = new File(path);
        File[] folder = dir.listFiles(new MyFilenameFilter("^.svn$"));
        if (folder == null) 
            return null; 
        for (int i = 0; i < folder.length; i++) { 
            if (folder[i].isDirectory()) {
            	TreeNode treeNode = new TreeNode(folder[i].getName(), null, false);
            	treeNode.setChildren(new ArrayList<TreeNode>());
            	folderList.add(treeNode);
            	searchFolders(folder[i].getAbsolutePath(), treeNode.getChildren()); 
            }
        }
        
		return folderList;
	}
}

class  MyFilenameFilter implements FilenameFilter {   
	private Pattern pattern = null;
  
    public MyFilenameFilter(String regex){  
        this.pattern = Pattern.compile(regex);
    }  

	@Override
	public boolean accept(File dir, String name) {
		if (pattern.matcher(name).matches()) return false;
		return true;
	} 
}
